package com.wmx.newspushmonitor.base;

import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.WindowManager;

import com.rhino.dialog.LoadingDialogFragment;
import com.rhino.dialog.impl.IOnDialogListener;
import com.rhino.ui.base.BaseSimpleTitleActivity;
import com.rhino.ui.utils.LogUtils;
import com.rhino.ui.utils.StatusBarUtils;
import com.rhino.ui.utils.net.NetWorkUtils;
import com.rhino.ui.utils.okhttp.Callback;
import com.rhino.ui.utils.okhttp.HttpParams;
import com.rhino.ui.utils.thread.ThreadPoolProxyFactory;
import com.rhino.ui.utils.ui.ToastUtils;
import com.wmx.newspushmonitor.NewsPushMonitorApplication;

import java.io.File;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Response;

/**
 * @author rhino
 * @since Create on 2018/9/19.
 **/
public abstract class BaseSimpleTitleHttpActivity<T extends ViewDataBinding> extends BaseSimpleTitleActivity {

    public LoadingDialogFragment mLoadingDialogFragment;
    public T dataBinding;

    /**
     * 没有网络
     **/
    public static final int EVENT_NETWORK_DISABLE = 0x0;
    /**
     * 请求成功
     **/
    public static final int EVENT_SUCCESS = 0x1;
    /**
     * 请求失败
     **/
    public static final int EVENT_FAILED = 0x2;
    /**
     * 请求过程
     **/
    public static final int EVENT_PROGRESS = 0x3;
    /**
     * 将请求结果放在handle处理，callback可以更新ui
     **/
    public CustomerHandler mHttpHandler = new CustomerHandler(this);
    /**
     * 自定义Handler
     */
    public static class CustomerHandler extends Handler {
        WeakReference<BaseSimpleTitleHttpActivity> weakReference;

        public CustomerHandler(BaseSimpleTitleHttpActivity arg) {
            this.weakReference = new WeakReference<>(arg);
        }

        @Override
        public void handleMessage(Message msg) {
            BaseSimpleTitleHttpActivity arg = weakReference.get();
            if (!arg.isFinishing()) {
                Bundle b = msg.getData();
                int event = b.getInt("event");
                String url = b.getString("url");
                String data = b.getString("data");
                Object reqData = msg.obj;
                arg.callbackHandler(event, url, data, reqData);
            }
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        mLoadingDialogFragment = new LoadingDialogFragment();
        mLoadingDialogFragment.setText("加载中");
        mLoadingDialogFragment.setIOnDialogListener(new IOnDialogListener<LoadingDialogFragment>() {
            @Override
            public void onStart(LoadingDialogFragment loadingDialogFragment) {
            }

            @Override
            public void onResume(LoadingDialogFragment loadingDialogFragment) {
            }

            @Override
            public void onPause(LoadingDialogFragment loadingDialogFragment) {
            }

            @Override
            public void onStop(LoadingDialogFragment loadingDialogFragment) {
            }

            @Override
            public void onDismiss(LoadingDialogFragment loadingDialogFragment) {
                onLoadingDialogCancel(loadingDialogFragment);
            }
        });
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
        StatusBarUtils.setStatusBarColor(this, Color.TRANSPARENT);
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        dismissLoadingDialog();
        mLoadingDialogFragment = null;
        mHttpHandler = null;
    }

    @Override
    public void setContentView(int layoutResID) {
        setContentView(getLayoutInflater().inflate(layoutResID, null, false));
    }

    @Override
    public void setContentView(View view) {
        super.setContentView(view);
        try {
            dataBinding = DataBindingUtil.bind(view);
        } catch (Exception e) {
        }
    }

    @Override
    public boolean initData() {
        return true;
    }

    /**
     * 加载对话框被取消监听
     *
     * @param loadingDialogFragment loadingDialogFragment
     */
    public void onLoadingDialogCancel(LoadingDialogFragment loadingDialogFragment) {

    }

    /**
     * 刷新加载对话框文字描述
     *
     * @param text 描述
     */
    public void updateLoadingDialogText(String text) {
        mLoadingDialogFragment.setText(text);
    }

    /**
     * 显示加载对话框
     **/
    public void showLoadingDialog(String text) {
        dismissLoadingDialog();
        if (null != mLoadingDialogFragment && !mLoadingDialogFragment.isAdded()) {
            updateLoadingDialogText(text);
            mLoadingDialogFragment.show(this);
        }
    }

    /**
     * 显示加载对话框
     **/
    public void showLoadingDialog() {
        dismissLoadingDialog();
        if (null != mLoadingDialogFragment && !mLoadingDialogFragment.isAdded()) {
            mLoadingDialogFragment.show(this);
        }
    }

    /**
     * 取消加载对话框
     **/
    public void dismissLoadingDialog() {
        if (null != mLoadingDialogFragment && mLoadingDialogFragment.isAdded() && !mLoadingDialogFragment.isDetached()) {
            mLoadingDialogFragment.dismissAllowingStateLoss();
        }
    }

    /**
     * 显示toast提示
     *
     * @param msg 提示
     */
    public void showToast(String msg) {
        ToastUtils.show(msg);
    }

    /**
     * 检查网络状态
     *
     * @return true 网络正常
     */
    public boolean checkNetWork() {
        if (!NetWorkUtils.isNetWorkAvailable(NewsPushMonitorApplication.getInstance())) {
            sendMsg(EVENT_NETWORK_DISABLE, "", "", null);
            dismissLoadingDialog();
            showToast("网络不可用");
            return false;
        }
        return true;
    }

    /**
     * 此处可以更新ui
     *
     * @param event   成功或失败
     * @param url     请求url
     * @param data    请求得到的数据
     * @param reqData 请求的数据
     */
    public void callbackHandler(int event, String url, String data, Object reqData) {
        LogUtils.i("event[" + event + "], url[" + url + "], data[" + data + "], reqData[" + reqData + "]");
    }

    /**
     * 发送消息
     *
     * @param event   请求结果EVENT_XXX
     * @param url     请求url
     * @param data    请求返回数据
     * @param reqData 请求数据
     */
    public void sendMsg(int event, String url, String data, Object reqData) {
        if (mHttpHandler == null) {
            return;
        }
        Message msg = mHttpHandler.obtainMessage();
        Bundle b = new Bundle();
        b.putInt("event", event);
        b.putString("url", url);
        b.putString("data", data);
        msg.setData(b);
        msg.obj = reqData;
        mHttpHandler.sendMessage(msg);
    }

    /**
     * 是否请求成功
     *
     * @param event 请求结果
     * @return true 成功
     */
    public boolean isHttpRequestSuccess(int event) {
        return EVENT_SUCCESS == event;
    }

    /**
     * 发起post请求
     *
     * @param url 请求rul
     */
    public void doPost(final String url) {
        doPost(url, null);
    }

    /**
     * 发起post请求
     *
     * @param url    请求rul
     * @param params 请求参数
     */
    public void doPost(final String url, HttpParams params) {
        doPost(url, params, null);
    }

    /**
     * 发起post请求
     *
     * @param url     请求rul
     * @param params  请求参数
     * @param reqData 请求数据
     */
    public void doPost(final String url, HttpParams params, final Object reqData) {
        if (!checkNetWork()) {
            return;
        }
        NewsPushMonitorApplication.getHttpRequest().doPost(url, params, new Callback() {

            @Override
            public void onFailure(Call arg0, IOException arg1) {
                sendMsg(EVENT_FAILED, url, arg1.toString(), reqData);
            }

            @Override
            public void onResponse(Call arg0, Response arg1)
                    throws IOException {
                sendMsg(EVENT_SUCCESS, url, arg1.body().string(), reqData);
            }
        });
    }

    /**
     * 发起post请求
     *
     * @param url    请求rul
     * @param paramsMap 请求参数
     */
    public void doPostByMap(final String url, Map<String, String> paramsMap) {
        doPostByMap(url, paramsMap, null);
    }

    /**
     * 发起post请求
     *
     * @param url     请求rul
     * @param paramsMap  请求参数
     * @param reqData 请求数据
     */
    public void doPostByMap(final String url, Map<String, String> paramsMap, final Object reqData) {
        if (!checkNetWork()) {
            return;
        }
        NewsPushMonitorApplication.getHttpRequest().doPostByMap(url, paramsMap, new Callback() {

            @Override
            public void onFailure(Call arg0, IOException arg1) {
                sendMsg(EVENT_FAILED, url, arg1.toString(), reqData);
            }

            @Override
            public void onResponse(Call arg0, Response arg1)
                    throws IOException {
                sendMsg(EVENT_SUCCESS, url, arg1.body().string(), reqData);
            }
        });
    }


    /**
     * 发起get请求
     *
     * @param url 请求rul
     */
    public void doGet(final String url) {
        doGet(url, null);
    }

    /**
     * 发起get请求
     *
     * @param url    请求rul
     * @param params 请求参数
     */
    public void doGet(final String url, HttpParams params) {
        doGet(url, params, null);
    }

    /**
     * 发起get请求
     *
     * @param url     请求rul
     * @param params  请求参数
     * @param reqData 请求数据
     */
    public void doGet(final String url, HttpParams params, final Object reqData) {
        if (!checkNetWork()) {
            return;
        }
        NewsPushMonitorApplication.getHttpRequest().doGet(url, params, new Callback() {

            @Override
            public void onFailure(Call arg0, IOException arg1) {
                sendMsg(EVENT_FAILED, url, arg1.toString(), reqData);
            }

            @Override
            public void onResponse(Call arg0, Response arg1)
                    throws IOException {
                sendMsg(EVENT_SUCCESS, url, arg1.body().string(), reqData);
            }
        });
    }

    /**
     * 发起get请求
     *
     * @param url     请求rul
     * @param paramsMap  请求参数
     */
    public void doGetByMap(final String url, Map<String, String> paramsMap) {
        doGetByMap(url, paramsMap, null);
    }

    /**
     * 发起get请求
     *
     * @param url     请求rul
     * @param paramsMap  请求参数
     * @param reqData 请求数据
     */
    public void doGetByMap(final String url, Map<String, String> paramsMap, final Object reqData) {
        if (!checkNetWork()) {
            return;
        }
        NewsPushMonitorApplication.getHttpRequest().doGetByMap(url, paramsMap, new Callback() {

            @Override
            public void onFailure(Call arg0, IOException arg1) {
                sendMsg(EVENT_FAILED, url, arg1.toString(), reqData);
            }

            @Override
            public void onResponse(Call arg0, Response arg1)
                    throws IOException {
                sendMsg(EVENT_SUCCESS, url, arg1.body().string(), reqData);
            }
        });
    }

}
